<script setup lang="ts">
import type {
  FormInstance,
} from 'element-plus'
import {
  ElDatePicker,
  ElForm,
  ElFormItem,
  ElInput,
} from 'element-plus'
import { defaultFormData, formRules } from '../index'
import type {
  CustomDialogInstance,
  EnergyBindItem,
} from '@/types'
import DictionaryPicker from '@/components/DictionaryPicker/DictionaryPicker.vue'

import { energyApi, measuringToolsApi } from '@/api'
import { merge } from 'lodash-es'
// import { Warning } from '@element-plus/icons-vue';

const props = defineProps<{
  title: string
  treeData?: any[]
  pointId: number
  isView: boolean
}>()
const emits = defineEmits<{
  (e: 'success'): void
}>()
const info = defineModel('data', {
  required: true,
  default: () => defaultFormData,
})
const [energyData, setEnergyData] = useState<
  EnergyBindItem[]
>([])

const dialogRef = ref<CustomDialogInstance | null>(null)
const formRef = ref<FormInstance | null>(null)
const rules = computed(() => {
  return merge(formRules, {
    verificationCycle: [{
      required: !!unref(info).verificationDate,
      message: '必填项',
    }],
    verificationDate: [{
      required: !!unref(info).verificationCycle,
      message: '必填项',
    }],
  })
})

const parentTreeData = computed(() => {
  return props.treeData?.filter(
    item => item.id !== info.value.id,
  )
})

function open() {
  dialogRef.value?.open()
}
function close() {
  dialogRef.value?.close()
}

async function clickConfirm(done: () => void) {
  if (props.isView) {
    done()
    close()
    return
  }
  try {
    await formRef.value?.validate()
    const params = {
      ...info.value,
      pointId: props.pointId,
    }
    removeUnnecessaryParams(params)
    await measuringToolsApi.saveOrUpdateMeasuringTools(
      params,
    )

    emits('success')
    done()
    close()
  }
  catch (error) {
    done()
  }
  finally {
    done()
  }
}
async function getEnergyData() {
  const { data: res }
    = await energyApi.queryEnterpriseBindList()
  setEnergyData(res)
}
function handlerEnergySelect(item: EnergyBindItem) {
  info.value.energyId = item.energyId
  info.value.energyCode = item.code
}
function handlerNextVerificationDate() {
  if (!info.value.verificationDate)
    return
  const d = new Date(info.value.verificationDate!)
  d.setDate(
    d.getDate() + (info.value.verificationCycle ?? 0),
  )
  info.value.nextVerificationDate = formatTime(
    d,
    'YYYY-MM-DD hh:mm:ss',
  )
}

watch(
  () => unref(info).verificationDate,
  (val: any) => {
    if (!val) {
      info.value.nextVerificationDate = ''
    }
  },
)

onBeforeMount(() => {
  getEnergyData()
})

defineExpose({
  open,
  close,
})
</script>

<template>
  <CustomDialog
    ref="dialogRef"
    :title="title"
    need-saving
    @confirm="clickConfirm"
  >
    <ElForm
      ref="formRef"
      class="clearfix"
      :model="info"
      :rules="rules"
      label-width="150px"
    >
      <ElFormItem label="上级计量器具" prop="parentId">
        <!-- <template #label>
          <span class="flex align-center">
            上级计量器具
            <el-tooltip
              content="不填为顶级"
              placement="top"
            >
              <el-icon
                class="c-pointer fs-16 margin-left-xs"
              >
                <Warning />
              </el-icon>
            </el-tooltip>
          </span>
        </template> -->
        <el-select
          v-model="info.parentId"
          :disabled="isView"
          filterable
          clearable
          class="width-fill"
        >
          <ElOption
            v-for="item in parentTreeData"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </ElFormItem>
      <ElFormItem label="计量器具名称" prop="name">
        <ElInput
          v-model.trim="info.name"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="计量器具编号" prop="code">
        <ElInput
          v-model.trim="info.code"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="计量器具类型" prop="type">
        <DictionaryPicker
          v-model="info.type"
          code="JI_LIANG_QI_JU_LEI_XING"
          clearable
          :disabled="isView"
        />
      </ElFormItem>
      <ElFormItem label="能源品种" prop="energyId">
        <ElSelect
          :model-value="info.energyId"
          :disabled="isView"
          clearable
          class="width-fill"
        >
          <ElOption
            v-for="item in energyData"
            :key="item.id"
            :value="item.energyId"
            :label="item.name"
            @click="handlerEnergySelect(item)"
          />
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="计量等级" prop="measurementLevel">
        <DictionaryPicker
          v-model="info.measurementLevel"
          :disabled="isView"
          code="JI_LIANG_DENG_JI"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="类型规格" prop="specification">
        <ElInput
          v-model.trim="info.specification"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="生产厂家" prop="factory">
        <ElInput
          v-model.trim="info.factory"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="精确度等级" prop="accuracyLevel">
        <ElInput
          v-model.trim="info.accuracyLevel"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="测量范围" prop="measuringRange">
        <ElInput
          v-model.trim="info.measuringRange"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem
        label="检定结果"
        prop="verificationResult"
      >
        <DictionaryPicker
          v-model="info.verificationResult"
          code="JIAN_DING_JIE_GUO"
          clearable
          :disabled="isView"
        />
      </ElFormItem>
      <ElFormItem label="检定周期(天)" prop="verificationCycle" :required="!!info.verificationDate">
        <ElInputNumber
          v-model="info.verificationCycle"
          :min="1"
          controls-position="right"
          :step="1"
          :disabled="isView"
          @change="handlerNextVerificationDate"
        />
      </ElFormItem>
      <ElFormItem label="检定机构">
        <ElInput
          v-model.trim="info.verificationMechanism"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="上次检定时间" prop="verificationDate" :required="!!info.verificationCycle">
        <ElDatePicker
          v-model="info.verificationDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          :disabled="isView"
          clearable
          @change="handlerNextVerificationDate"
        />
      </ElFormItem>
      <ElFormItem label="下次检定时间">
        <ElDatePicker
          v-model="info.nextVerificationDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          clearable
          disabled
        />
      </ElFormItem>
      <ElFormItem label="未检定原因">
        <ElInput
          v-model.trim="info.notVerificationReason"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem
        label="安装位置"
        prop="installationLocation"
      >
        <ElInput
          v-model.trim="info.installationLocation"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="安装厂家">
        <ElInput
          v-model.trim="info.installationManufacturer"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>

      <ElFormItem label="安装时间" prop="installationTime">
        <ElDatePicker
          v-model="info.installationTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="接入系统">
        <ElInput
          v-model.trim="info.accessSystem"
          maxlength="20"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="接入状态" prop="accessStatus">
        <el-select
          v-model="info.accessStatus"
          :disabled="isView"
          clearable
        >
          <el-option label="已接入" :value="1" />
          <el-option label="未接入" :value="2" />
        </el-select>
      </ElFormItem>
      <ElFormItem label="运行状态" prop="workingStatus">
        <DictionaryPicker
          v-model="info.workingStatus"
          code="YUN_XING_ZHUANG_TAI"
          :disabled="isView"
          clearable
        />
      </ElFormItem>

      <!-- <ElFormItem label="检定日期" prop="verificationDate">
        <ElDatePicker
          v-model="info.verificationDate"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
        ></ElDatePicker>
      </ElFormItem>
      <ElFormItem
        label="检定有效期时间"
        prop="effectiveTime"
      >
        <ElDatePicker
          v-model="info.effectiveTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
        ></ElDatePicker>
      </ElFormItem>
      <ElFormItem label="检定到期时间" prop="expireTime">
        <ElDatePicker
          v-model="info.expireTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
        ></ElDatePicker>
      </ElFormItem> -->

      <!-- <ElFormItem label="计量等级" prop="measurementLevel">
        <ElInput v-model="info.measurementLevel"></ElInput>
      </ElFormItem> -->

      <ElFormItem label="状态发生时间" prop="clearTime">
        <ElDatePicker
          v-model="info.statusTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          :disabled="isView"
          clearable
        />
      </ElFormItem>

      <ElFormItem label="更换时间" prop="replacementTime">
        <ElDatePicker
          v-model="info.replacementTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
      <ElFormItem label="清零时间" prop="clearTime">
        <ElDatePicker
          v-model="info.clearTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm"
          :disabled="isView"
          clearable
        />
      </ElFormItem>
    </ElForm>
  </CustomDialog>
</template>

<style scoped>
.clearfix :deep(.el-form-item) {
  float: left;
  width: 50%;
}
</style>
